package com.senven.api.aspect;

import com.senven.api.annotation.LogInfo;
import com.senven.api.service.LogService;
import com.senven.api.utils.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
/**
 * 日志切面
 * 全局日志监控
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private LogService logService;

    // 设置切点
    @Pointcut("execution(* com.senven.api.controller.*.*(..))")
    private void point(){}

    // 前置通知，获取当前操作的session
    /*
    @Before(value="point()")
    public void beforeLog(JoinPoint  pjp){
        // 获取绑定线程的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取绑定该线程的session
        HttpSession session = request.getSession();
        // 获得当前操作的管理员
        String account = (String) session.getAttribute("account");
    }*/

    // 后置通知，根据返回结果生成日志
    @AfterReturning(returning = "result", value = "point()")
    public void afterLog(JoinPoint  pjp, Object result){
        // 获取绑定线程的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        // 获取方法上面的注解
        LogInfo logInfo = method.getAnnotation(LogInfo.class);
        // 判断该方法是否要被记录日志
        if(logInfo != null){
            // 得到当前的操作
            String operate = logInfo.operateInfo();
            String type = logInfo.operateType();
            // 检测当前操作是否成功
            if(result != null || (int)result >= 1){
                logService.insertLog(LogUtil.getLog(type, operate,"操作成功",request));
            }else {
                logService.insertLog(LogUtil.getLog(type, operate,"操作失败",request));
            }
        }
    }
}